const express = require("express");
const multer  = require('multer')
const sd = require('silly-datetime')
const mkdirp = require("mkdirp")
const path = require("path")


// 基础上传
/* var storage = multer.diskStorage({
  // 文件保存路径
  destination: function (req, file, cb) {
    cb(null, 'public/upload') // 存放路径，必须先创建该文件夹
  },
  // 设置上传的文件的名称
  filename: function (req, file, cb) {
    let fileFormat = file.originalname.split('.')
    cb(null, Date.now() + "." + fileFormat[fileFormat.length -1])
  }
}) */

// 按日期生成上传目录
let storage = multer.diskStorage({
  // 配置文件保存路径
  destination: async (req, file, cb) => {
    // 1.获取当前时间
    let day = sd.format(new Date(), "YYYYMMDD")
    // 2.生成路径
    let dir = path.join('public/upload', day)
    // 3.创建目录
    await mkdirp(dir);
    cb(null, dir)
  },
  // 设置上传的文件的名称
  filename: function (req, file, cb) {
    let fileFormat = file.originalname.split('.')
    cb(null, Date.now() + "." + fileFormat[fileFormat.length -1])
  }
})

 
var upload = multer({ storage: storage })

let router = express.Router();

router.get("/", (req, res) => {
  res.send("导航列表")
})
router.get("/add", (req, res) => {
  res.render("nav/add", {});
})
router.get("/edit", (req, res) => {
  res.send("修改导航")
})

// 上传一张图片
/* router.post("/doAdd", upload.single('pic'), (req, res) => {
  res.send({
    file: req.file,
    body: req.body
  })
}) */


// 上传多张图片
const cpUpload = upload.fields([
  { name: "avatar", maxCount: 1},
  { name: "pic", maxCount: 8}
])
router.post("/doAdd", cpUpload, (req, res) => {
  res.send({
    file: req.file,
    body: req.body
  })
})


router.post("/doEdit", (req, res) => {
  res.send("执行修改导航")
})


module.exports = router